import Foundation
import Combine

// 传感器数据服务协议
protocol SensorDataServiceProtocol {
    var sensorData: SensorDataCollection { get }
    var sensorDataPublisher: Published<SensorDataCollection>.Publisher { get }
    
    func startMonitoring()
    func stopMonitoring()
    func setRefreshRate(seconds: Double)
}

// 传感器数据服务
class SensorDataService: ObservableObject, SensorDataServiceProtocol {
    // MARK: - 属性
    @Published var sensorData: SensorDataCollection
    var sensorDataPublisher: Published<SensorDataCollection>.Publisher { $sensorData }
    
    // 连接服务
    private var connectionService: CarConnectionService
    
    // 数据更新定时器
    private var updateTimer: Timer?
    
    // 刷新频率（秒）
    private var refreshRate: Double
    
    // 应用设置
    private var appSettings: AppSettings
    
    // MARK: - 初始化方法
    init(connectionService: CarConnectionService, settings: AppSettings) {
        self.connectionService = connectionService
        self.refreshRate = settings.dataRefreshRate
        self.appSettings = settings
        
        // 初始化默认传感器数据
        self.sensorData = SensorDataCollection.sample
        
        // 如果启用了自动连接，则开始监控
        if settings.isAutoConnectEnabled {
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
                self?.startMonitoring()
            }
        }
    }
    
    // MARK: - 公共方法
    func startMonitoring() {
        // 仅在已连接状态下开始监控
        guard connectionService.isConnected else {
            print("无法开始监控，设备未连接")
            return
        }
        
        // 停止现有定时器
        stopMonitoring()
        
        // 创建新的定时器，定期更新传感器数据
        updateTimer = Timer.scheduledTimer(withTimeInterval: refreshRate, repeats: true) { [weak self] _ in
            self?.updateSensorData()
        }
        
        // 立即更新一次数据
        updateSensorData()
        
        print("已开始监控传感器数据，刷新频率: \(refreshRate)秒")
    }
    
    func stopMonitoring() {
        // 停止更新定时器
        updateTimer?.invalidate()
        updateTimer = nil
        
        print("已停止监控传感器数据")
    }
    
    func setRefreshRate(seconds: Double) {
        // 更新刷新频率
        self.refreshRate = seconds
        
        // 如果正在监控，则重启定时器
        if updateTimer != nil {
            stopMonitoring()
            startMonitoring()
        }
        
        print("已设置传感器数据刷新频率为: \(seconds)秒")
    }
    
    // MARK: - 私有方法
    private func updateSensorData() {
        // 模拟从设备获取传感器数据
        // 在实际应用中，这里会通过蓝牙或WiFi从设备获取真实数据
        
        // 温度：模拟在22-28度之间波动，带有少量随机变化
        let temperature = 24.0 + sin(Date().timeIntervalSince1970 * 0.0005) * 2.0 + Double.random(in: -0.5...0.5)
        
        // 湿度：模拟在55-75%之间波动
        let humidity = 65.0 + sin(Date().timeIntervalSince1970 * 0.0003) * 10.0 + Double.random(in: -2.0...2.0)
        
        // PM2.5：模拟在20-40之间波动
        let pm25 = 28.0 + sin(Date().timeIntervalSince1970 * 0.0008) * 8.0 + Double.random(in: -2.0...2.0)
        
        // 光照：模拟在500-1200之间波动
        let light = 845.0 + sin(Date().timeIntervalSince1970 * 0.0002) * 300.0 + Double.random(in: -50.0...50.0)
        
        // 烟雾：模拟在5-20之间波动
        let smoke = 12.0 + sin(Date().timeIntervalSince1970 * 0.0006) * 5.0 + Double.random(in: -1.0...1.0)
        
        // 气压：模拟在1000-1025之间波动
        let pressure = 1013.0 + sin(Date().timeIntervalSince1970 * 0.0001) * 12.0 + Double.random(in: -1.0...1.0)
        
        // 更新传感器数据
        let currentTime = Date()
        sensorData = SensorDataCollection(
            temperature: SensorDataPoint(type: .temperature, value: temperature, timestamp: currentTime, appSettings: appSettings),
            humidity: SensorDataPoint(type: .humidity, value: humidity, timestamp: currentTime, appSettings: appSettings),
            pm25: SensorDataPoint(type: .pm25, value: pm25, timestamp: currentTime, appSettings: appSettings),
            light: SensorDataPoint(type: .light, value: light, timestamp: currentTime, appSettings: appSettings),
            smoke: SensorDataPoint(type: .smoke, value: smoke, timestamp: currentTime, appSettings: appSettings),
            pressure: SensorDataPoint(type: .pressure, value: pressure, timestamp: currentTime, appSettings: appSettings),
            lastUpdated: currentTime
        )
    }
    
    deinit {
        // 清理定时器
        updateTimer?.invalidate()
    }
} 